import { expect } from '@jest/globals';
import path from 'path';

import { runHvigorAsync } from '../../common/common';
import {addOhPackageDps, commonJson5Operation, readJson5} from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';
import fse from "fs-extra";

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.StaticLibrary]
};

/**
 * @param {Project} project
 * @param {TestTaskOption} taskConfig
 * @param {ICaseRecord} record
 * @return res
 */
const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const moduleRootPath = project.getModule('staticLibrary').moduleRootPath();
  // eslint-disable-next-line max-len
  const commands: string[] = '--mode module -p product=default -p module=staticLibrary@default assembleHar --analyze=normal --parallel --incremental --no-daemon'.split(' ');
  await commonJson5Operation(path.resolve(project.projectRootPath(), 'hvigor/hvigor-config.json5'), async (json) => {
    json.properties = {
      "ohos.nativeResolver": false
    };
    return json;
  });
  await commonJson5Operation(path.resolve(project.projectRootPath(), 'oh-package.json5'), async (json) => {
    json.dependencies = json.devDependencies;
    delete json.devDependencies;
    return json;
  });
  await addOhPackageDps(project.projectRootPath(), {});
  await commonJson5Operation(path.resolve(project.projectRootPath(), 'build-profile.json5'), async (json) => {
    json.app.products[0].buildOption = {
      strictMode: {
        useNormalizedOHMUrl: true
      }
    };
    return json;
  });
  await commonJson5Operation(path.resolve(moduleRootPath, 'build-profile.json5'), async (json) => {
    json.buildOption.arkOptions = json.buildOption.arkOptions || {};
    json.buildOption.arkOptions.byteCodeHar = true;
    return json;
  });
  const code = `
  import { describe } from '@ohos/hypium';
  @Component
  export struct Hello {
    build() {
      Text(typeof describe)
    }
  }
  `;
  fse.writeFileSync(`${moduleRootPath}/src/main/ets/Hello.ets`, code);
  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('执行字节码HAR构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  const filesInfoPath = path.resolve(moduleRootPath, 'build', 'default', 'cache', 'default', 'default@HarCompileArkTS', 'esmodule', 'debug', 'filesInfo.txt');
  const content = fse.readFileSync(filesInfoPath, 'utf-8');
  expect(content.includes('@ohos/hypium')).toEqual(false);
};

TestCaseBuilder.builder()
  .caseName('byte-code-har-exclude-dependencies')
  // eslint-disable-next-line max-len
  .description('字节码HAR，不允许包含其依赖的代码')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L0).build())
  .testFun(testfun)
  .load();
